<?php

namespace api\modules\backend\models;

use Yii;
use \yii\db\ActiveRecord;
use common\commands\Common;

/**
 * Role Model
 *
 * @author Fong <xiaofeng.zhang@suppernovachina.com>
 */
class Role extends ActiveRecord
{
    const STATUS_DELETED = 0;
    const STATUS_ACTIVE = 1;

    /**
     * @inheritdoc
     */
    public static function tableName()
    {
        return '{{%role}}';
    }

    /**
     * @inheritdoc
     */
    public static function primaryKey()
    {
        return ['role_id'];
    }

    /**
     * Define rules for validation
     */
    public function rules()
    {
        return [
            [['role_name', 'mobile', 'active'], 'required'],
            [['role_name'], 'string', 'length' => [2, 20]],
            [['account'], 'required', 'on' => 'create'],
            [['account'], 'string', 'length' => [4, 20]],
            [['account', 'mobile'], 'unique'],
            [['password_hash'], 'required', 'on' => 'create'],
            [['role'], 'in', 'range' => [0, 1, 2]],
            [['mobile'], 'integer'],
            [['mobile'], 'match', 'pattern' => '/^1[34578]\d{9}$/'],
            [['account'], 'match', 'pattern' => '/^(\w){4,20}$/'],
            [['active'], 'in', 'range' => [0, 1]]
        ];
    }

    /**
     * Generates password hash from password and sets it to the model
     *
     * @param string $password
     */
    public function setPassword($password)
    {
        $this->password_hash = Yii::$app->security->generatePasswordHash($password);
    }

    /**
     * Finds user by username
     *
     * @param string $username
     * @return static|null
     */
    public static function findByAccount($account)
    {
        return static::findOne(['account' => $account, 'active' => self::STATUS_ACTIVE]);
    }

    /**
     * apiTokenIsValid - 令牌验证
     * @param $token
     * @return bool
     */
    public static function apiTokenIsValid($token)
    {
        if (empty($token)) return false;

        $role = static::findOne(['access_token' => $token, 'active' => self::STATUS_ACTIVE]);//获取当前登录人信息

        if (empty($role)) return false;

        $apiTokenExpire = $role->access_token_expire;
        $expire = Yii::$app->params['role.apiTokenExpire'];

        if ($apiTokenExpire < time()) {//判断是否过期，如果过期时间戳小于当前时间戳  则为已经过期   如果过期时间戳大于当前时间戳则代表token还有效
            return false;
        } else {
            $newApiTokenExpire = time() + $expire;//新的过期时间
            $role->access_token_expire = $newApiTokenExpire;
            $role->last_ip = Yii::$app->request->getUserIP();
            $role->save();

            return true;
        }
    }

    /**
     * generateApiToken - 生成令牌
     * @throws \yii\base\Exception
     */
    public function generateApiToken()
    {
        $this->access_token = Yii::$app->security->generateRandomString() . '_' . time();//获取token
        $expire = Yii::$app->params['role.apiTokenExpire'];
        $this->access_token_expire = time() + $expire;//设置token过期时间
        $this->update_time = time();//登录时间
        $this->last_ip = Yii::$app->request->getUserIP();
    }

    /**
     * validatePassword - 密码验证
     * @param $password
     * @return bool
     *
     */
    public function validatePassword($password)
    {
        return Yii::$app->security->validatePassword($password, $this->password_hash);
    }
}
